import React, { useCallback, useRef } from 'react';
import LazyLoad from '../lazy-load';

export type ExposureProps = {
  /** 曝光时回调 */
  onExposure: () => void;
  /** 是否曝光一次 */
  onece?: boolean;
  /** 曝光监听滚动容器 */
  container?: Element | Document | null | undefined;
};

export const Exposure = ({ onExposure, onece, container }: ExposureProps) => {
  const exposureRef = useRef(null);

  const callback = useCallback(() => {
    const ref = exposureRef.current as unknown as HTMLElement;
    const repored = ref?.dataset?.reported;
    if (onece) {
      if (repored === 'false') {
        onExposure && onExposure();
        ref.dataset.reported = 'true';
      }
    } else {
      onExposure && onExposure();
    }
  }, [onExposure]);

  return (
    <div data-reported={false} ref={exposureRef}>
      <LazyLoad
        container={container || null}
        onVisible={(visible) => {
          visible && callback();
        }}
      >
        <div></div>
      </LazyLoad>
    </div>
  );
};
